package com.lntea.netty.chat;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Title: ZhangServerHandler.java<br>
 * Description:  <br>
 *
 * @author LC
 * @date 2020/9/24 15:13
 */
public class ZhangServerHandler extends ChannelInboundHandlerAdapter {

    private int dialogId;

    /**
     * 客户端接入时，发送请求
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 双工模式，循环发送开场白
        new Thread(() -> {
            while(dialogId++ < 50) {
                HuTongMessage message = new HuTongMessage(dialogId, HuTongChatEnum.ZHANG_1.getDialog());
                System.out.println(message.toString());
                //ByteBuf message = Unpooled.copiedBuffer("server dialog", CharsetUtil.UTF_8);
                //System.out.println(message.toString(CharsetUtil.UTF_8));
                ctx.writeAndFlush(message);
            }
        }).start();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // ByteBuf message = (ByteBuf) msg;
        // System.out.println(message.toString(CharsetUtil.UTF_8));
        HuTongMessage message = (HuTongMessage) msg;
        message.setMsgContent(HuTongChatEnum.nextDialog(message.getMsgContent()));
        System.out.println(message.toString());
        if (message.getMsgContent() == null) {
            ctx.flush();
        } else {
            ctx.writeAndFlush(message);
        }
        // ByteBuf writeBuf = Unpooled.copiedBuffer("receive msg:", CharsetUtil.UTF_8);
        // ctx.write(writeBuf);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        /*ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
                .addListener(ChannelFutureListener.CLOSE);*/
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
